package com.chang.spring6.iocXML.detest;

import com.alibaba.druid.pool.DruidDataSource;
import com.chang.spring6.iocXML.life.Water;
import com.chang.spring6.iocXML.scope.User;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.sql.SQLException;

public class TestDemo {
    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beanDIplus.xml");
        Student bean = context.getBean(Student.class);
        System.out.println(bean);
    }

    @Test
    public void test2() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beanDIplus.xml");
        Class bean = context.getBean(Class.class);
        System.out.println(bean);
    }

    @Test
    public void test3() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beanDIplus.xml");
        Teacher bean = context.getBean(Teacher.class);
        System.out.println(bean);
    }

    @Test
    public void test4() throws SQLException {
        ApplicationContext context = new ClassPathXmlApplicationContext("jdbc.xml");
        DruidDataSource dataSource = (DruidDataSource) context.getBean("druidDataSource");
        System.out.println(dataSource.getUrl());
    }

    @Test
    public void testBeanScope() {
        ApplicationContext context = new ClassPathXmlApplicationContext("scope.xml");
        User bean = context.getBean(User.class);
        User bean2 = context.getBean(User.class);
        System.out.println(bean == bean2);
    }

    @Test
    public void testBeanLife() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beanLife.xml");
        Water water = context.getBean("water", Water.class);
        System.out.println("6,bean对象创建完成，开始使用>>>>>>>");
        System.out.println(water);
        context.close(); // 销毁容器
    }


    // xml配置文件标明的类是导入了特定接口的对象 MyFactoryBean implements FactoryBean<Water>
    // 由于导入Water对象时，Water对象的创建过程被MyFactoryBean重新定义了，所以创建出来的对象，自带了在MyFactoryBean中被定义的默认name属性

    // 注意要点，xml配置文件中引入的类是自定义的MyFactoryBean，这个类导入了添加Water泛型的FactoryBean接口，并重写了方法
    // 这样直接获取自定义工厂类就能获取工厂生产的Bean对象
    @Test
    public void factoryBeanTest() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("BeanFactoryBean.xml");
        Water water = (Water) context.getBean("water");
        System.out.println(water);
        System.out.println(water.getName());
    }
}
